package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * @ClassName StringToBaseEnumConverterFactory
 * @Author 波
 * @Date 2024/6/26 14:29
 * 因为浏览器发送的数据只有String类型，而我们接受实体类是enum类型，所以需要先转换成枚举类型才可以接受数据
 * StringToBaseEnumConverterFactory这个类就是一个将String类型转换成枚举类型的工厂类
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
                for (T t : targetType.getEnumConstants()) {
                    if(t.getCode().equals(Integer.valueOf(source))){
                        return t;
                    }
                }
                throw new IllegalArgumentException("非法的枚举值:" + source);
            }
        };
    }
}
